#include "defs.h"
#define extern_
#include "data.h"
#undef extern_
#include "decl.h"
#include <errno.h>

/*
 * Initialize global variables.
 */
static void init(void)
{
    Line = 1;
    Putback = '\n';
}

/*
 * Print out a usage if started incorrectly.
 */
static void usage(char *prog)
{
    fprintf(stderr, "Usage: %s infile\n", prog);
    exit(1);
}

/*
 * Main program: check arguments and print a usage
 * if we don't have an argument. Open up the input
 * file and call scanfile() to scan the tokens in it.
 */
int main(int argc, char *argv[])
{
    struct ASTnode *tree;

    if (argc != 2)
        usage(argv[0]);

    init();

    /* open up the input file */
    if ((Infile = fopen(argv[1], "r")) == NULL) {
        fprintf(stderr, "Unable to open %s: %s\n", argv[1], strerror(errno));
        return 1;
    }

    /* create the output file */
    if ((Outfile = fopen("out.s", "w")) == NULL) {
        fprintf(stderr, "Unable to create out.s: %s\n", strerror(errno));
        return 1;
    }

    scan(&Token);                    /* get the first token from the input */
    genpreamble();                   /* output the preamble */
    while (1) {
        tree = function_declaration();      /* parse the statements in main function */
        genAST(tree, NOREG, 0, NOLABEL);    /* generate assembly code for it */
        if (Token.token == T_EOF)           /* stop when we have reached EOF */
            break;
    }

    fclose(Outfile);

    return 0;
}
